import React, {useEffect, useState} from "react";
import {
    Button,
    Col,
    Form,
    Input,
    message,
    Modal,
    Row,
    Select,
    Space,
    Switch,
    Table,
    TableProps,
    Tooltip,
    Tree
} from 'antd';
import renderIcons from "@/components/CustomIconSelector/conponents";


import {changeUserStatus, delUser, listUser} from "@/api/system/user.ts";
import {DatePicker} from 'antd';
import {DeleteOutlined, PlusOutlined} from "@ant-design/icons";
import EditorRoleView from "@/views/system/role/component/EditorRoleView.tsx";
import {changeRoleStatus, delRole, listRole} from "@/api/system/role.ts";
import DataPermissionsView from "@/views/system/role/component/DataPermissionsView.tsx";
import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { globalMessage } from "@/utils/message";
// 定义组件的 props 类型
interface MyComponentProps {
    SelectOption: (e: any) => void;
    type?:'checkbox' | 'radio';
}
const RoleTableView: React.FC<MyComponentProps> = (props) => {
    const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined,
        beginTime: null,
        endTime: null,

    };

    interface DataType {
    }

    const [form] = Form.useForm();
    const [forceUpdateKey, setForceUpdateKey] = useState(0); // 用于强制更新组件的 key
    const [dataList, setDataList] = useState<DataType[]>([]);
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '角色编号',
            dataIndex: 'roleId',
            key: 'roleId',
            align: 'center'
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
            key: 'roleName',
            align: 'center'
        },
        {
            title: '权限字符',
            dataIndex: 'roleKey',
            key: 'roleKey',
            align: 'center'
        }, {
            title: '显示顺序',
            dataIndex: 'roleSort',
            key: 'roleSort',
            align: 'center'
        }, {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (_, record:any) => (
                <Switch key={forceUpdateKey + record.roleId} defaultValue={record.status === "0"}
                        onChange={(checked, event) => onChangeStatus(checked, event, record)} checkedChildren="开启"
                        unCheckedChildren="关闭"/>
            )
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
    ];
    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [openDataPermissions, setOpenDataPermissions] = useState<boolean>(false);
    useEffect(() => {
        getList();
    }, [queryParams]);  // 监听 queryParams 变化，调用 getList

    /** 查询用户列表 */
    function getList() {
        listRole(queryParams).then((res:any) => {
            setDataList(res.rows.map((item: any) => ({
                ...item,
                key: item.roleId // 使用 userId 作为唯一的 key
            })))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    function handleSearch() {
        form.validateFields().then(values => {
            console.log(values, 'values')
            setQueryParams(prevQueryParams => ({
                ...queryParams,
                roleName: values.roleName,
                status: values.status,
                roleKey: values.roleKey,
                "params[beginTime]": values.dateRange ? values.dateRange[0].format("YYYY-MM-DD") : null,
                "params[endTime]": values.dateRange ? values.dateRange[1].format("YYYY-MM-DD") : null,
            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        form.resetFields();
        setQueryParams(initialQueryParams); // 重置为初始状态
    }

    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };


    const onChangeStatus = (checked: boolean, event: any, value: any) => {
        console.log(checked, event, value);
        const text = value.status === "0" ? "启用" : "停用";
        Modal.confirm({
            title: '系统提示',
            content: (`确认要"${text}"+"${value.roleName}"角色吗？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                changeRoleStatus(value.roleId, checked === false ? "1" : "0").then((res:any) => {
                    if (res?.code === 200) {
                         globalMessage().info("修改成功").then(r => {
                        })
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作
                setForceUpdateKey(prevKey => prevKey + 1); // 更新 key 以强制重新渲染组件
            },
        });
    }


    const SelectTableChange = (record, selected, selectedRows,) => {
        props.SelectOption(selectedRows)
    }
    const rowSelection: TableProps<DataType>['rowSelection'] = {
        type: props.type,
        onSelect: SelectTableChange,
        onSelectAll: SelectTableChange,
    }
    return (
        <div className='home'>
            <Row gutter={20} style={{paddingTop: "20px"}}>
                <Col span={24}>
                    <div><Form
                        form={form}
                        name="customized_form_controls"
                        style={{marginTop: 10, marginLeft: 10, marginBottom: 10}}
                       layout={useResponsiveLayout("inline")}>
                        <Form.Item
                            name="roleName"
                            label="角色名称">
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            name="roleKey"
                            label="权限字符">
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            name="status"
                            label="状态">
                            <Select
                                style={{
                                    width: 120,
                                }}

                                allowClear
                                options={[
                                    {
                                        value: 0,
                                        label: '正常',
                                    }, {
                                        value: 1,
                                        label: '停用',
                                    },
                                ]}
                            />
                        </Form.Item>

                        <Form.Item
                            name="dateRange"
                            label="日期">
                            <DatePicker.RangePicker format="YYYY-MM-DD"/>
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                                marginRight: 20,
                            }}>
                                查询
                            </Button>
                            <Button type="primary" htmlType="reset" onClick={resetSearch}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form></div>
                    <Table<DataType>  scroll={{ x: true }} columns={columns} dataSource={dataList} pagination={{
                        current: queryParams.pageNum,
                        pageSize: queryParams.pageSize,
                        total: total,
                        showSizeChanger: true, // 显示分页尺寸切换器
                        pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                        onChange:handleTableChange
                    }}  rowSelection={rowSelection}
                    />
                </Col>
            </Row>
        </div>
    )
};
export default RoleTableView;
